<!--
 * @Author: lichunyao licy529529@163.com
 * @Date: 2022-07-12 16:37:44
 * @LastEditors: lichunyao licy529529@163.com
 * @LastEditTime: 2022-07-26 09:36:20
 * @FilePath: \digital_workshop\_web\src\views\main\saleorder\addForm.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <a-modal
    title="新增销售订单"
    width="80%"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <saleorder-table-form-item
          :dataSource="workOrderList"
          :proList="list.proList"
          :plaNum="form.getFieldValue('plaNum') ? form.getFieldValue('plaNum') : null"
          @add="
            ({ tableData }) => {
              workOrderList = tableData
            }
          "
          @del="
            ({ tableData }) => {
              workOrderList = tableData
            }
          "
        />
        <a-form-item label="备注信息" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
          <a-textarea :rows="3" placeholder="请输入备注信息" v-decorator="['remarks']" />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>
<script>
import { saleOrderAdd } from '@/api/modular/main/saleorder/saleOrderManage'
import { proList } from '@/api/modular/main/pro/proManage'
import saleorderTableFormItem from '@/views/main/saleorder/saleorderTableFormItem'
export default {
  components: {
    saleorderTableFormItem
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      labelCol_T: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol_T: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      list: {
        // 产品
        proList: [],
        badItem: []
      },
      allWorkRouteStepList: [],
      allWorkRouteList: [],
      allWorkStepList: [],
      // 销售订单
      workOrderList: [],
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this)
    }
  },
  provide() {
    return {
      getProList: this.getProList
    }
  },
  methods: {
    // 初始化方法
    async add(record) {
      this.time = new Date().toLocaleDateString()
      await this.getProList()
      this.visible = true
      const inTypeOption = this.$options
      this.inTypeData = inTypeOption.filters['dictData']('in_type')
      if (!record) {
        return
      }
      if (record.workOrderList && record.workOrderList.length > 0) {
        this.workOrderList = record.workOrderList.map((item) => {
          item.id = undefined
          return item
        })
      }
    },
    // 获取proList表单
    async getProList() {
      this.list.proList = []
      var promise = proList().then((res) => {
        this.list.proList = res.data
      })
      await promise
      return this.list.proList
    },
    proChange(val) {
      let workRouteId = ''
      let workRSData = {}
      const stepRoutList = []
      this.list.proList.forEach(pro => {
        if (pro.id === val) {
          workRouteId = pro.workRouteId
          if (!workRouteId || !this.allWorkRouteList) {
            this.$message.warn('该产品未绑定工艺路线，请手动添加工序')
            return
          }
          // 获取产品id对应的工艺路线
          this.allWorkRouteList.forEach(route => {
            if (route.id === workRouteId) {
              workRSData = route || {}
            }
          })
          // 获取对应的工艺路线与工序关系列表
          this.allWorkRouteStepList.forEach(item => {
            if (item.workRouteId === workRouteId) {
              const stepRoute = item
              this.allWorkStepList.forEach(step => {
                if (step.id === item.workStepId) {
                  stepRoute['mulBadItem'] = step.mulBadItem
                }
              })
              stepRoutList.push(stepRoute)
            }
          })
          if (stepRoutList && stepRoutList.length > 0) {
            workRSData['workStepRouteList'] = stepRoutList
          }
        }
      })
      this.$refs.child.handleWorkRouteConfirm(workRSData)
    },
    /**
     * 提交表单
     */
    // 问题：没添加产品时也会创建订单成功
    handleSubmit() {
      const {
        form: { validateFields }
      } = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        if (!errors) {
          for (const key in values) {
            if (typeof values[key] === 'object' && values[key] != null) {
              values[key] = JSON.stringify(values[key])
            }
          }
          // 过滤空的值
          if (this.workOrderList.length === 0) {
            this.confirmLoading = false
            return this.$message.error('产品名称不能为空')
          }
          values.workOrderList = this.workOrderList || null
          // 过滤空值
          values.code = values.code ? values.code.trim() : values.code
          saleOrderAdd(values)
            .then((res) => {
              if (res.success) {
                this.$message.success('新增成功')
                this.confirmLoading = false
                this.$emit('ok', values)
                this.handleCancel()
              } else {
                this.$message.error(res.message) // + res.message
              }
            })
            .finally((res) => {
              this.confirmLoading = false
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.timeDateString = ''
      this.time = ''
      this.workOrderList = []
      this.form.getFieldDecorator('time', { initialValue: null })
      this.form.resetFields()
      this.visible = false
    }
  }
}
</script>
